package com.example.campus.search.controller;

import cn.hutool.json.JSONUtil;
import com.copyctrl.campus.common.domain.PassageDTO;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

/**
 * @author:JH
 * @version:1.0
 */
@RestController
@RequestMapping("/put")
public class PutController {
    @PutMapping("/passage")
    public void add(@RequestBody Map<String,String> body){
        String passage = body.get("passage");
        PassageDTO passageDTO = JSONUtil.toBean(passage, PassageDTO.class);
        // 1.准备Request
        IndexRequest request = new IndexRequest("passages").id(passageDTO.getId().toString());
        // 2.准备请求参数DSL，其实就是文档的JSON字符串
        request.source(passage, XContentType.JSON);
        try(RestHighLevelClient client= new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://1.14.107.219:9200")
        ));) {
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
